package samsung.sds.system.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import samsung.sds.systemMonitor.exceptionMonitor.model.ExceptionEntity;
import samsung.sds.systemMonitor.exceptionMonitor.service.ExceptionMonitorService;

public class ExceptionFilter implements Filter {
	private String errorPage;
	private ApplicationContext ctx;
	private ExceptionMonitorService exceptionMonitorServiceImpl;
	
	public void init(FilterConfig filterConfig) throws ServletException {
		errorPage = filterConfig.getInitParameter("exceptionPage");
		if (null == errorPage || "".equals(errorPage)) {
			errorPage = "/WEB-INF/jsp/common/exception.jsp";
		}
		// 加载由Spring管理的bean
		ServletContext context = filterConfig.getServletContext();  
        ctx = WebApplicationContextUtils.getWebApplicationContext(context);  
        exceptionMonitorServiceImpl = (ExceptionMonitorService) ctx.getBean("exceptionMonitorServiceImpl");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest requestHttp = (HttpServletRequest) request;
		HttpServletResponse responseHttp = (HttpServletResponse) response;
		// 捕获异常
		try {
			chain.doFilter(requestHttp, responseHttp);
		} catch (Throwable e) {
			if (e instanceof Throwable) {
				//封装异常
				ExceptionEntity exception = exceptionMonitorServiceImpl.packageException(e, requestHttp);
				//异常入库
				exceptionMonitorServiceImpl.insertEntity(exception);
				// 查看request类型
				String header = requestHttp.getHeader("x-requested-with");
				if ("XMLHttpRequest".equalsIgnoreCase(header)) {// ajax request
					response.setContentType("text/plain;charset=UTF-8");
					responseHttp.setStatus(500);
					responseHttp.getWriter().write(getExceptionMessage(e));
				} else {
					requestHttp.setAttribute("exception", getExceptionMessage(e));// 存储业务异常信息类
					requestHttp.getRequestDispatcher(errorPage).forward(
							requestHttp, responseHttp);// 跳转到信息提示页面！！
				}
				e.printStackTrace();
			}

		}
	}

	public void destroy() {
		
	}
	
	private String getExceptionMessage(Throwable e){		
		try{
			if(e.getCause().getCause()==null){
				return e.getCause().getMessage();
			}else{
				return e.getCause().getCause().getMessage();
			}
		}catch(Exception e1){
			return e.getMessage();
		}
	}
	

}
